using System;
using System.Data;
using System.Data.Common;
using System.Text;
using Adoor.Expression;

namespace Adoor.Relational.RelationalSource
{
	/// <summary>
	/// Summary description for SqlRelationSourceTrace.
	/// </summary>
	public class SqlRelationSourceTrace : RelationalSourceTrace
	{
		public SqlRelationSourceTrace()
		{
			
		}

		public override string GetTrace(string commandText, System.Data.IDbCommand command)
		{
			StringBuilder trace = new StringBuilder();
			if (command.Parameters.Count != 0)
			{
				bool comma = false;
				foreach(IDbDataParameter prm in command.Parameters)
				{
					if (comma)
						trace.Append(Environment.NewLine);
					comma = true;

					object val = prm.Value;
					trace.Append("declare ");
					trace.Append(prm.ParameterName);
					trace.Append(" ");
					trace.Append(GetDBTypeString(prm));
					trace.Append(Environment.NewLine);
					trace.Append("set ");
					trace.Append(prm.ParameterName);
					trace.Append(" = ");
					if(val == null || val == DBNull.Value)
					{
						trace.Append("NULL");
					}
					else
					{
						trace.Append("'");
						if(val is bool)
						{
							if(true.Equals(val))
								trace.Append(1);
							else
								trace.Append(0);
						}
						else if(val is DateTime)
						{
							trace.Append(((DateTime) val).ToString("yyyy-MM-ddTHH:mm:ss"));
						}
						else
							trace.Append(Convert.ToString(val, System.Globalization.CultureInfo.InvariantCulture));
						trace.Append("'");
					}
					trace.Append(Environment.NewLine);
				}
			}
			trace.Append(formatCommandText(commandText));
			return trace.ToString();
		}

		private string formatCommandText(string commandText)
		{
			StringBuilder result = new StringBuilder(commandText);
			result.Replace(" on ", Environment.NewLine + "\ton ");
			result.Replace(" join ", Environment.NewLine + "join ");
			result.Replace(" from ", Environment.NewLine + "from ");
			result.Replace("(select ", "(" + Environment.NewLine + "\tselect ");
			result.Replace(" inner" + Environment.NewLine + "join", Environment.NewLine + "inner join");
			result.Replace(" left outer" + Environment.NewLine + "join", Environment.NewLine + "left outer join");
			result.Replace(" left" + Environment.NewLine + "join", Environment.NewLine + "left join");
			result.Replace("join ( ", "join (" + Environment.NewLine);
			result.Replace(" union all ", Environment.NewLine  + "union all" + Environment.NewLine);
			result.Replace(" where ", Environment.NewLine  + "where" + Environment.NewLine);
			result.Replace(" from ", Environment.NewLine  + "from " );
			result.Replace(" group by", Environment.NewLine  + "group by" );
			result.Replace(" having ", Environment.NewLine  + "having " );
			result.Replace(" order by", Environment.NewLine  + "order by" );
			return result.ToString();
		}
	}
}
